#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""风险管理器模块
负责评估交易风险和执行风险控制策略"""

import json
import os
from datetime import datetime
from utils import Logger, FileUtils

class RiskManager:
    """风险管理器
    负责评估交易风险并实施风险控制措施"""
    
    def __init__(self):
        """初始化风险管理器"""
        # 风险规则
        self.risk_rules = {
            "max_position_per_stock": 100000,  # 单只股票最大持仓金额
            "max_single_order": 50000,  # 单笔交易最大金额
            "daily_trading_limit": 200000,  # 单日交易总限额
            "max_position_percentage": 0.3,  # 单只股票最大持仓比例
            "max_leverage": 1.0,  # 最大杠杆比例
            "stop_loss_percentage": 0.1,  # 止损比例
            "take_profit_percentage": 0.2  # 止盈比例
        }
        
        # 加载风险规则配置
        self.load_risk_rules()
        
        Logger.log_info("风险管理器初始化完成")
    
    def load_risk_rules(self):
        """从配置文件加载风险规则"""
        try:
            config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config", "risk_rules.json")
            
            if os.path.exists(config_path):
                rules_data = FileUtils.read_json(config_path)
                if rules_data:
                    self.risk_rules.update(rules_data)
                    Logger.log_info(f"成功从配置文件加载风险规则: {config_path}")
            else:
                Logger.log_warning(f"风险规则配置文件不存在: {config_path}")
        except Exception as e:
            Logger.log_error(f"加载风险规则失败: {str(e)}")
    
    def evaluate_trade_risk(self, trade_data):
        """评估交易风险
        
        Args:
            trade_data: 交易数据字典，包含股票代码、订单类型、数量、价格等
            
        Returns:
            dict: 风险评估结果
        """
        try:
            stock_code = trade_data.get("stock_code")
            order_type = trade_data.get("order_type", "buy")
            quantity = trade_data.get("quantity", 0)
            price = trade_data.get("price", 0)
            stock_name = f"股票{stock_code}"
            is_buy = order_type.lower() == "buy"
            
            # 计算交易金额
            trade_amount = price * quantity
            
            # 1. 检查单笔交易限额
            if trade_amount > self.risk_rules["max_single_order"]:
                message = f"交易金额 {trade_amount} 超过单笔交易最大限额 {self.risk_rules['max_single_order']}"
                Logger.log_warning(message)
                return {
                    "risk_level": "high",
                    "pass": False,
                    "message": message
                }
            
            # 2. 模拟检查单日交易限额
            daily_trades = self.get_daily_trades()
            if sum(trade['amount'] for trade in daily_trades) + trade_amount > self.risk_rules["daily_trading_limit"]:
                message = f"今日交易总金额将超过限额 {self.risk_rules['daily_trading_limit']}"
                Logger.log_warning(message)
                return {
                    "risk_level": "high",
                    "pass": False,
                    "message": message
                }
            
            # 3. 模拟检查单只股票持仓限额
            current_position = self.get_current_position(stock_code)
            if current_position + (trade_amount if is_buy else -trade_amount) > self.risk_rules["max_position_per_stock"]:
                message = f"股票 {stock_code} 的持仓将超过最大限额 {self.risk_rules['max_position_per_stock']}"
                Logger.log_warning(message)
                return {
                    "risk_level": "high",
                    "pass": False,
                    "message": message
                }
            
            # 风险评估通过
            message = f"交易 {stock_name}({stock_code}) {quantity}股 @ {price} 通过风险评估"
            Logger.log_info(message)
            return {
                "risk_level": "normal",
                "pass": True,
                "message": message
            }
        except Exception as e:
            error_message = f"风险评估异常: {str(e)}"
            Logger.log_error(error_message)
            return {
                "risk_level": "error",
                "pass": False,
                "message": error_message
            }
    
    def get_daily_trades(self):
        """获取今日交易记录
        
        Returns:
            list: 今日交易记录列表
        """
        # 模拟获取今日交易记录
        return [
            {"stock_code": "SH600000", "amount": 20000, "time": datetime.now().strftime('%H:%M:%S')},
            {"stock_code": "SZ000001", "amount": 15000, "time": datetime.now().strftime('%H:%M:%S')}
        ]
    
    def get_current_position(self, stock_code):
        """获取当前持仓金额
        
        Args:
            stock_code: 股票代码
            
        Returns:
            float: 持仓金额
        """
        # 模拟获取当前持仓金额
        # 返回一个基于股票代码的伪随机值
        position_map = {
            "SH600000": 30000,
            "SZ000001": 25000,
            "SH600519": 80000
        }
        
        return position_map.get(stock_code, 0)